<?php

defined('SYSPATH') or die('Access error!');

class Model_Setting extends Model
{

    /**
     *  获取用户组的数据
     * 
     * @param type $where
     * @return type
     */
    public function get_setting_group($where = '')
    {
        $where = !empty($where) ? ' AND ' . $where : " AND type='group'";
        $where .= ' ORDER BY position,id';
        $setting_group_temp = $this->get_results($where);
        $setting_group = array();
        if (count($setting_group_temp) > 0)
        {
            foreach ($setting_group_temp as $key => $value)
            {
                $value['sub'] = $this->get_sub_setting($value['id']);
                $setting_group[] = $value;
            }
            unset($setting_group_temp);
        }
        return count($setting_group) > 0 ? $setting_group : array();
    }

    /**
     *  获取某个组下的配置数据
     * @param type $id
     * @return type
     */
    public function get_sub_setting($id)
    {
        $sub_setting = $this->get_results(' AND parent_id=' . $id, 'name,id,value,code');
        return count($sub_setting) ? $sub_setting : array();
    }

    public function get_all_setting()
    {
        $setting_cache = Cache::instance()->read(SYSTEM_SETTING_CACHE_PATH.'setting.php');
        if(Arr::validate_arr($setting_cache)){
            return $setting_cache;
        }
        $all_setting = $this->get_results();
        if(count($all_setting)>0){
            $all_setting = $this->set_setting_code_value($all_setting);
        }
        return count($all_setting) ? $all_setting : array();
    }

    /**
     *  更新子类配置文件
     * @param type $data
     * @return boolean
     */
    public function update_sub_setting($data)
    {
        if (count($data) > 0)
        {
            $i = 0;
            foreach ($data as $key => $value)
            {
                $this->update(array('value' => $value), array('code' => $key));
                $i++;
            }
            return $i > 0 ? TRUE : FALSE;
        }
        return TRUE;
    }

    public function set_setting_code_value($setting = array())
    {
        if (count($setting) == 0)
        {
            return array();
        }
        foreach ($setting as $key => $value)
        {
            $setting_temp[$value['code']] = $value['value'];
        }
        return  $setting_temp;
    }

}